<template>
  <div class="ticketing-list-container">
    <el-card shadow="never" class="mb-5 border-box">
      <el-form :inline="true" :model="searchForm" class="flex flex-wrap items-center">
        <el-form-item label="门票名称">
          <el-input
            v-model="searchForm.formName" 
            placeholder="请输入门票名称"
          />
        </el-form-item>
        <el-form-item label="门票来源">
          <el-input
            v-model="searchForm.sourceTitle"
            placeholder="请输入门票来源"
          />
        </el-form-item>
        <!-- <el-form-item label="门票类型">
          <el-input
            v-model="searchForm.ticketingType"
            placeholder="请输入门票类型"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增购票
          </el-button>
        </el-form-item>
      </el-form>
     </el-card>

    <div class="page-content">
      <el-table
        v-loading="isLoading"
        :data="ticketingList"
        style="width: 100%"
        v-show="!showEmpty"
        height="calc(100vh - 330px)"
      >
        <el-table-column prop="formName" label="门票名称" />
        <el-table-column label="门票封面" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.parsedImage.length"
              :src="row.parsedImage[0].path"
              :preview-src-list="[row.parsedImage[0].path]"
              :initial-index="0"
              preview-teleported
              fit="cover"
              class="ticket-image w-[50px] h-[50px] cursor-pointer"
              :z-index="3000"
            />
            <!-- <el-empty v-else description="暂无图片" :image-size="40"  class="ticket-image w-[40px] h-[40px]" /> -->
          </template>
        </el-table-column>
        <el-table-column prop="sourceTitle" label="门票来源" />
        <!-- <el-table-column prop="ticketingType" label="门票类型" /> -->
        <el-table-column prop="miniProgramJump" label="跳转链接" />
        <!-- <el-table-column prop="paranJson" label="大麦|买票上大麦" >
          <template #default="{ row }">
            <QrcodeVue
            :value="`https://wuhansportpark.com/weixin/${row.id}`"
            :size="50"
            level="H"
            render-as="svg"
          />
          </template>
         
        </el-table-column> -->
        <el-table-column label="操作" width="130">
          <template #default="{ row }">
            <el-button type="primary"  size="small"  link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger"  size="small" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="showEmpty"  class="flex justify-center h-[calc(100vh-330px)]" description="暂无数据" />

      <div class="flex justify-center mt-5">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>

      <el-dialog
        v-model="dialogVisible"
        :title="form.id ? '编辑购票' : '新增购票'"
        width="600px"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="门票名称" prop="formName">
            <el-input v-model="form.formName" placeholder="请输入门票名称" />
          </el-form-item>
          <el-form-item label="门票封面" prop="image">
            <MyUpload
                :file-list="fileList"
                :limit="1"
                :width="'120px'"
                :height="'120px'"
                @deleteFile="deleteFile"
                @uploadFileSuccess="success"
              />
          </el-form-item>
          <el-form-item label="门票来源" prop="sourceTitle">
            <el-input v-model="form.sourceTitle" placeholder="请输入门票来源" />
          </el-form-item>
          <!-- <el-form-item label="门票类型" prop="ticketingType">
            <el-input
              v-model="form.ticketingType"
              placeholder="请输入门票类型" 
            />
          </el-form-item> -->
          <el-form-item label="跳转链接" prop="miniProgramJump">
            <el-input
              v-model="form.miniProgramJump"
              placeholder="请输入跳转链接" 
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit(formRef)">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { Search } from '@element-plus/icons-vue'
import type { ElMessageBox, ElMessage, FormInstance, FormRules } from 'element-plus'
 import QrcodeVue from 'qrcode.vue'
import { zidingyipiaowubiaodanvo } from '@/api/4a/types'
import {
  scenicTicketingCustomFormPageTicketingCustomUsingPost,
  scenicTicketingCustomFormSaveTicketingCustomUsingPost,
  scenicTicketingCustomFormUpdateTicketingCustomUsingPut,
  scenicTicketingCustomFormGetByIdTicketingCustomUsingGet,
  scenicTicketingCustomFormDeleteTicketingCustomUsingDelete
} from '@/api/4a/goupiaoguanli'
import { scenicWebsiteSaveMenuPhotosUsingPost } from '@/api/4a/guanwang'

const ticketingList = ref<zidingyipiaowubiaodanvo[]>([])
const total = ref(0)
const isLoading = ref(true)
const currentPage = ref(1)
const searchForm = reactive({
  formName: '',
  sourceTitle: '',
  ticketingType: 0,
})
const pageSize = ref(10)
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({

  formName: [
    { required: true, message: '请输入门票名称', trigger: 'blur' },
  ],
  // sourceTitle: [
  //   { required: true, message: '请输入门票来源', trigger: 'blur' },
  // ],
  // onePrice: [
  //   { required: true, message: '请输入单价', trigger: 'blur' },
  // ],
  // maxNumber: [
  //   { required: true, message: '请输入容量', trigger: 'blur' },
  // ],
  // oneMaxNumber: [
  //   { required: true, message: '请输入限购数量', trigger: 'blur' },
  // ],
  // ticketingType: [
  //   { required: true, message: '请输入门票类型', trigger: 'change' },
  // ],
})


const form = reactive({
  formName: '',
  sourceTitle: '',
  onePrice: undefined,
  maxNumber: undefined,
  oneMaxNumber: undefined,
  ticketingType: 0,
  miniProgramJump:undefined,
  remark: '',
  image: '',
  objId: undefined,
  objType: 0,
  paramJson: '',
  imageList:'',
})

// 请求参数
const queryParams = computed(() => {
  return {
    current: currentPage.value,
    size: pageSize.value,
    objType:0,
    ...searchForm
  }
})

// 空状态判断
const showEmpty = computed(() => {
  return !isLoading.value && (!ticketingList.value || ticketingList.value.length === 0)
})

// 封面
const fileList = computed({
    get() {
      return JSON.parse(form.image || '[]')
    },
    set(value) {
      form.image = value
    }
  })

  const success = (a:any) => {
    fileList.value.push(a.data)
    fileList.value = JSON.stringify(fileList.value)
  }

  const deleteFile = (params:any) => {
    fileList.value = JSON.stringify(fileList.value.filter((item:any) => item.path !== params.path))
  }

// 获取购票列表
const getTicketingList = async () => {
  isLoading.value = true
  try {
    const res = await scenicTicketingCustomFormPageTicketingCustomUsingPost({
      body: queryParams.value
    })
    if (res.code === 0) {
      // 预处理图片数据
      ticketingList.value = (res.data?.list || []).map(item => ({
        ...item,
        parsedImage: (() => {
          try {
            const images = JSON.parse(item.image || '[]')
            return Array.isArray(images) ? images : []
          } catch (e) {
            return []
          }
        })()
      }))
      total.value = res.data?.total || 0
    } else {
      ElMessage.error('获取列表失败')
    }
  } catch (error) {
    ElMessage.error('获取列表失败')
  } finally {
    isLoading.value = false
  }
}

// 处理页码大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getTicketingList()
}

// 分页切换
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTicketingList()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getTicketingList()
}

// 重置
const handleReset = () => {
  searchForm.formName = ''
  searchForm.sourceTitle = ''
  searchForm.ticketingType = 0
  handleSearch()
}

// 新增
const handleAdd = (formEl: FormInstance | undefined) => {
  formRef.value?.resetFields();
  dialogVisible.value = true
}

// 编辑
const handleEdit = async(row:any) => {
  dialogVisible.value = true
  const res = await scenicTicketingCustomFormGetByIdTicketingCustomUsingGet({
    params: {
      id: row.id
    }
  })
  if (res.code === 0 && res.data) {
    Object.assign(form, res.data)
    if(res.data.image == '0'){
      form.image = ''
    }
    // if(res.data.image === '0' && res.data.image == null) {
    //   form.imageList = ''
    // } else {
    //   form.imageList = res.data.image ? JSON.stringify([{path: res.data.image}]) : ''
    // }
    
  } else {
    ElMessage.error('获取详情失败')
  }
}
// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该门票吗？', '删除门票', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    isLoading.value = true
    console.log(row.id);
    
    const response = await scenicTicketingCustomFormDeleteTicketingCustomUsingDelete({
      params: {id:row.id}
    })
    
    if (response.data) {
      ElMessage.success('删除成功')
      handleSearch() // 刷新列表
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除门票失败:', error)
      ElMessage.error('删除门票失败')
    }
  } finally {
    isLoading.value = false
  }
}

// 提交
const handleSubmit = async (formEl: FormInstance | undefined) => {
  // if(form.imageList){
  //     const list = JSON.parse(form.imageList)
  //     if(list.length > 0){
  //       form.image = list[0].path
  //   }
  //   }else{
  //     form.image='0'
  //   }
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (form.id) {
          res = await scenicTicketingCustomFormUpdateTicketingCustomUsingPut({
            body: form
          })
        } else {
          res = await scenicTicketingCustomFormSaveTicketingCustomUsingPost({
            body: form
          })
        }
        
        if (res.code === 0) {
          ElMessage.success(form.id ? '修改成功' : '添加成功')
          dialogVisible.value = false
          getTicketingList()
        } else {
          ElMessage.error(res.msg || (form.id ? '修改失败' : '添加失败'))
        }
      } catch (error) {
        ElMessage.error(form.id ? '修改失败' : '添加失败')
      }
      //   try {
      //   let res
      //     res = await scenicWebsiteSaveMenuPhotosUsingPost({
      //       body: {
      //         current: 1,
      //         size: 10,
      //         menuId:13,
      //         ...form
      //       }
      //     })
      //   if (res.code === 0) {
      //     ElMessage.success(form.id ? '修改成功' : '添加成功')
      //     dialogVisible.value = false
      //     // getTicketingList()
      //   } else {
      //     ElMessage.error(res.msg || (form.id ? '修改失败' : '添加失败'))
      //   }
      // } catch (error) {
      //   ElMessage.error(form.id ? '修改失败' : '添加失败')
      // }
    }
  })
}

onMounted(() => {
  getTicketingList()
})
</script>

<style lang="scss" scoped>
.ticketing-list-container {
  // padding: 20px;

  .filter-section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    margin-bottom: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 5%);

    .left-section {
      display: flex;
      gap: 16px;
      align-items: center;

      .search-box {
        // width: 300px;

        .search-input {
          width: 100%;
        }
      }
    }

    .filter-box {
      .el-select {
        width: 150px;
      }
    }
  }

  .page-content {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
.border-box {
    border-radius: 8px !important;
    :deep(.el-card__body){
      padding-bottom: 0 !important;
    }
  }
</style> 